//
//  HMComposeTypeView.swift
//  HMWeibo12
//
//  Created by iOS on 16/9/25.
//  Copyright © 2016年 iOS. All rights reserved.
//

import UIKit
import pop

/// 发微博选择类型的View
class HMComposeTypeView: UIView {

    /// 模糊的背景
    @IBOutlet weak var backgroundView: UIVisualEffectView!
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    /// 分割线
    @IBOutlet weak var separatorView: UIImageView!
    
    /// 返回按钮
    @IBOutlet weak var backButton: UIButton!
    
    /// 删除按钮
    @IBOutlet weak var deleteButton: UIButton!
    
    /// 删除按钮CenterX
    @IBOutlet weak var deleteButtonCenterXCons: NSLayoutConstraint!
    
    /// 返回按钮CenterX
    @IBOutlet weak var backButtonCenterXCons: NSLayoutConstraint!
    /// 第一页所有按钮
    private var firstPageButtons = [HMComposeButton]()
    
    /// 第二页所有按钮
    private var secondPageButtons = [HMComposeButton]()
    
    class func composeTypeView() -> HMComposeTypeView {
        return Bundle.main.loadNibNamed("HMComposeTypeView", owner: nil, options: nil)?.last as! HMComposeTypeView
    }
    
    /// 显示
    func show() -> Void {
        // 显示到window上面
//        UIApplication.shared.keyWindow?.addSubview(self)
        UIApplication.shared.keyWindow?.rootViewController?.view.addSubview(self)
        
        // 设置frame
        self.frame = UIScreen.main.bounds
        
        // 背景渐变动画
        let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        // 起始值
        animation.fromValue = 0
        // 结束值
        animation.toValue = 1
        animation.duration = 0.5
        
        backgroundView.pop_add(animation, forKey: "alpha")
        
        // 按钮动画
        for (index, button) in firstPageButtons.enumerated() {
            // 弹簧动画
            let springAnimation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            springAnimation.fromValue = button.center.y + 350
            springAnimation.toValue = button.center.y
            springAnimation.springBounciness = 8
            springAnimation.springSpeed = 8
            
//            CACurrentMediaTime()// 时钟芯片
//            print("CACurrentMediaTime = \(CACurrentMediaTime())")
            // 动画开始时间, 当前时间+ 延迟时间
            springAnimation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            
            button.pop_add(springAnimation, forKey: "spring")
        }
    }
    
    /// 关闭
    func dismiss() -> Void {
        // 按钮动画下来,背景渐变,移除view
        let buttons: [HMComposeButton]
        if scrollView.contentOffset.x == 0 {
            buttons = firstPageButtons
        } else {
            buttons = secondPageButtons
        }
        
        // 动画下去
        for (index, button) in buttons.reversed().enumerated() {
            let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            animation.fromValue = button.center.y
            animation.toValue = button.center.y + 350
            
            animation.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            
            button.pop_add(animation, forKey: "spring")
            
            if index == 0 {
                animation.completionBlock = { (_, _) -> Void in
                    let alpha: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
                    alpha.fromValue = 1
                    alpha.toValue = 0
                    alpha.duration = 0.5
                    
                    self.backgroundView.pop_add(alpha, forKey: "alpha")
                    
                    alpha.completionBlock = { (_, _) in
                        self.removeFromSuperview()
                    }
                }
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        // 加载数据
        let models = loadComposeButtonModel()
        
        for (index, model) in models.enumerated() {
            // 按钮宽高
            let size = CGSize(width: 100, height: 100)
            // 列数
            let numberOfColumn = 3
            
            // 间距
            let margin = (UIScreen.width - CGFloat(numberOfColumn) * size.width) / (CGFloat(numberOfColumn) + 1)
            // 在哪列
            let column = index % numberOfColumn
            // 在哪行
            var row = index / numberOfColumn
            
            // 偏移值
            var offset: CGFloat = 0
            if index >= 6 {
                // 特殊处理
                offset = UIScreen.width
                row -= 2
            }
            
            // x
            let x = offset + margin + CGFloat(column) * (size.width + margin)
            // y
            let y = CGFloat(row) * (size.height + margin)
            
            // 计算frame
            let frame = CGRect(x: x, y: y, width: size.width, height: size.height)
            
            // 创建按钮
            let button = HMComposeButton.composeButton(model: model)
            button.frame = frame
            button.addTarget(self, action: #selector(buttonDidClick(button:)), for: .touchUpInside)
            
            scrollView.addSubview(button)
            
            // 添加到对应的数组中,方便后续处理
            if index < 6 {
                firstPageButtons.append(button)
            } else {
                secondPageButtons.append(button)
            }
        }
        
        scrollView.contentSize = CGSize(width: UIScreen.width * 2, height: 0)
    }
    
    /// 10个按钮点击事件
    func buttonDidClick(button: HMComposeButton) -> Void {
        print("button \(button.model)")
        if button.model!.isMore {
            print("点击更多按钮")
            showMore()
            return
        }
        
        // 普通按钮, 点中的放大(2),其他的缩小(0.5),大家透明度0.5
        let buttons: [HMComposeButton]
        if scrollView.contentOffset.x == 0 {
            buttons = firstPageButtons
        } else {
            buttons = secondPageButtons
        }
        
        for (index, btn) in buttons.enumerated() {
            
            // 点中的按钮的缩放比例2,其他0.5
            let scale = btn == button ? 2 : 0.5
            
            let animation: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
//            animation.fromValue = 1
            // 包装成NSValue
            // NSValue的构造函数cgPint,提示的时候cg要小写
            animation.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            animation.duration = 0.5
            
            btn.pop_add(animation, forKey: "scale")
            
            // 透明度动画
            let alpha: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            alpha.fromValue = 1
            alpha.toValue = 0.5
            btn.pop_add(alpha, forKey: "alpha")
            
            if index == 0 {
                alpha.completionBlock = { (_, _) in
//                    self.dismiss()
                    // swift中一个完整的类名: 产品名称.类名
                    let productName = Bundle.main.infoDictionary!["CFBundleName"] as! String
                    
                    // 类名字符串
                    let fullClassString = productName + "." + button.model!.vcName!
                    
                    // AnyClass ==> 类名.Type
//                    let aa: UITableViewCell.Type = UITableViewCell.self
                    
                    // class
                    if let vcClass = NSClassFromString(fullClassString) as? UIViewController.Type {
                        
                        // 使用类名创建对象
                        let viewController = vcClass.init()
                        
                        // 跳转控制器
//                        print("跳转控制器: \(button.model?.vcName)")
                        let navVC = UINavigationController(rootViewController: viewController)
                        UIApplication.shared.keyWindow?.rootViewController?.present(navVC, animated: true, completion: {
                            self.removeFromSuperview()
                        })
                    }
                }
            }
        }
    }
    
    /// 处理跟多按钮点击事件
    private func showMore() {
        // scrollView滚动到下一页
        scrollView.setContentOffset(CGPoint(x: UIScreen.width, y: 0), animated: true)
        
        let offset = UIScreen.width / 4
        
        // 显示返回按钮,分割线
        backButton.isHidden = false
        separatorView.isHidden = false
        
        backButtonCenterXCons.constant = -offset
        deleteButtonCenterXCons.constant = offset
        
        separatorView.alpha = 0
        UIView.animate(withDuration: 0.25) {
            self.separatorView.alpha = 1
            self.layoutIfNeeded()
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss()
    }
    
    /// 关闭
    @IBAction func deleteButtonDidClick(_ sender: AnyObject) {
        dismiss()
    }
    
    /// 显示上一页
    @IBAction func backButtonDidClick(_ sender: AnyObject) {
        // scrollView滚回上一页
        scrollView.setContentOffset(CGPoint(), animated: true)
        
        backButtonCenterXCons.constant = 0
        deleteButtonCenterXCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.separatorView.alpha = 0
            }) { (_) in
                self.separatorView.isHidden = true
                self.backButton.isHidden = true
        }
    }
    
    // 加载数据
    private func loadComposeButtonModel() -> [HMComposeButtonModel] {
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        let array = NSArray(contentsOfFile: path!) as? [[String: Any]]
        
        var models = [HMComposeButtonModel]()
        
        for dict in array! {
            // 字典转模型
            let model = HMComposeButtonModel(dict: dict)
            
            models.append(model)
        }
        
        return models
    }
}
